 #!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import urllib
import os.path
import os

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from modules import config
from modules import download
from modules import service
from ui import mainwindow
from ui import configwindow
from ui import links

print sys.platform

print sys.argv

IMGDIR = 'img/'
LOCALE = 'locale/'
if not os.path.exists( IMGDIR ):
	IMGDIR = '../Resources/' #FOR MAC APP BUNDLE :)
	LOCALE = '../Resources/locale/'
	if not os.path.exists( IMGDIR ):
		IMGDIR = sys.argv[0].replace('qapid.exe', '') + 'img/' #FOR WIN32
		LOCALE = sys.argv[0].replace('qapid.exe', '') + 'locale/'

class Tray(QWidget):
	def __init__(self):
		QWidget.__init__(self)
		self.createActions()
		self.createIcon()
        self.createWindow()

		if not config.loadConf('show_icon') == 'yes':
			if sys.platform == 'darwin':
				QApplication.setQuitOnLastWindowClosed(False)
			else:
				QApplication.setQuitOnLastWindowClosed(True)
				self.window.show()
			self.tray.hide()
		else:
			QApplication.setQuitOnLastWindowClosed(False)
			self.tray.show()
		
		self.closed = True
		
		if config.loadConf('columnsset'):
			i = 0
			for v in config.loadConf('columnsset').split(':'):
				self.window.ui.download.setColumnWidth( i, int(v) )
				i = i + 1
		
	def createActions(self):
		self.restore = QAction( self.tr("&Restore Main Window"), self)
		QObject.connect( self.restore, SIGNAL("triggered()"), self.restoreWindow )

		self.config = QAction( self.tr("&Configuration"), self)
		QObject.connect( self.config, SIGNAL("triggered()"), self.restoreConfig )
		
		self.quit = QAction( self.tr("&Quit"), self)
		QObject.connect( self.quit, SIGNAL("triggered()"), self.quita )

	def createIcon(self):
		self.trayMenu = QMenu(self)
		self.trayMenu.addAction( self.restore )
		self.trayMenu.addAction( self.config )
		self.trayMenu.addSeparator()
		self.trayMenu.addAction( self.quit )

		self.tray = QSystemTrayIcon(self)
		self.tray.setContextMenu(self.trayMenu)
		self.tray.setToolTip( self.tr('Qapid - download manager') )
		self.tray.setIcon( QIcon(IMGDIR+'icon.png') )

		if sys.platform == 'darwin':
			self.setupMac()

		QObject.connect( self.tray, SIGNAL("activated( QSystemTrayIcon::ActivationReason )"), self.trayClick )

	def setupMac(self):
		self.dockMenu = QMenu(self)
		self.dockMenu.addAction( self.restore )
		self.dockMenu.addAction( self.config )
		qt_mac_set_dock_menu( self.dockMenu )
		
		self.window.ui.menubar.setParent( None )
		
	def createWindow(self):
		self.window = MainWindow(self)

	def restoreWindow(self):
		if self.window.isVisible():
			self.window.close()
		else:
			self.window.show()

	def restoreConfig(self):
		self.window.config.show()

	def trayClick( self, reason ):
		if not sys.platform == 'darwin':
			if reason == QSystemTrayIcon.Trigger or reason == QSystemTrayIcon.DoubleClick:
				self.restoreWindow()
			elif reason == QSystemTrayIcon.MiddleClick:
				self.restoreConfig()
		
	def quita(self):
		''''i = 0
		for item in self.window.ui.download.items( QMimeData() ):
			i = i + 1
		print i
		if i > 0:
			msg = QMessageBox( self.parent )
			msg.setText( self.tr("You are downloading file(s), are you sure to close?") )
			msg.setWindowTitle( self.tr("Close?") )
			msg.setIcon( QMessageBox.Question )
			nob = msg.addButton( self.tr("No"), QMessageBox.ActionRole )
			ovb = msg.addButton( self.tr("Yes"), QMessageBox.RejectRole )
			msg.exec_()
			if msg.clickedButton() == nob:
				return False
		'''
		columns = 4
		sizes = []
		i = 0
		
		while i <= columns:
			sizes.append( str( self.window.ui.download.columnWidth( i ) ) )
			i = i + 1
		
		a = ':'
		config.saveConf('columnsset', a.join( sizes ) )
		self.tray.hide()
		QApplication.quit()

class MainWindow(QMainWindow):
	def __init__(self, parent = None):
		QMainWindow.__init__(self, parent)
		self.parent = parent
		self.ui = mainwindow.Ui_MainWindow()
		self.ui.setupUi(self)
		
		screen = QDesktopWidget().screenGeometry()
		size =	self.geometry()

		self.move( ( screen.width() - size.width() ) / 2, ( screen.height() - size.height() ) / 2)

		self.setMaximumWidth( size.width() )
		self.setMaximumHeight( size.height() )
		
		self.setMinimumWidth( size.width() )
		self.setMinimumHeight( size.height() )

		self.setWindowTitle( QString( self.tr("Qapid - download manager") ) )

		if not sys.platform == 'darwin':
			self.setWindowIcon( self.parent.tray.icon() )

		self.config = ConfigWindow( self )
		self.links = LinksWindow( self ) 
		
		self.ui.openDir.setIcon( QIcon(IMGDIR+'opendir.png') )
		self.ui.openDir.setToolTip( self.tr('Open downloads dir') )
		
		self.ui.downloadButton.setIcon( QIcon( IMGDIR + 'add.png' ) )
		self.ui.downloadButton.setToolTip( self.tr("Add link(s)") )
		
		self.ui.pushButton.setIcon( QIcon( IMGDIR + 'remove.png' ) )
		self.ui.pushButton.setToolTip( self.tr("Remove link(s)") )

		self.createActions()
		
		self.isDownloading = False

		self.downloads = []
 
	def createActions(self):
		QObject.connect( self.ui.downloadButton, SIGNAL("clicked()"), self.showLinks )
	
		QObject.connect( self.ui.pushButton, SIGNAL("clicked()"), self.removeDownload )
		
		QObject.connect( self.ui.openDir, SIGNAL("clicked()"), self.openDownload )

		QObject.connect( self.ui.actionConfig, SIGNAL("triggered()"), self.parent.restoreConfig )

		QObject.connect( self.ui.actionQuit, SIGNAL("triggered()"), self.parent.quita )
		
		QObject.connect( self.ui.helpAbout, SIGNAL("triggered()"), self.about )
		
		QObject.connect( self.ui.helpQt, SIGNAL("triggered()"), self.aboutQt )
		
		QObject.connect( self.ui.actionAdd_links, SIGNAL("triggered()"), self.showLinks )
		
	def showLinks(self):
		self.links.show()
		
	def download(self):
		for url in self.links.ui.linksEdit.document().toPlainText().split("\n"):
		    url.remove(" ")
		    url = str( url )
		    print "["+url+"]"
		    if not url:
		    	return False
		    self.downloads.append( download.Download( url, self ) )
		self.links.ui.linksEdit.setPlainText( QString('') )

	def removeDownload(self):
		for item in self.ui.download.selectedItems():
			for dwl in self.downloads:
				if dwl.item == item:
					if dwl.progressBar.value() == 100 and dwl.progressBar.maximum() == 100:
						dwl.kill()
						return True
					
					if dwl.progressBar.value() == 0 and dwl.progressBar.maximum() == 1:
						dwl.kill()
						return True
										
					msg = QMessageBox( self.parent )
					msg.setText( self.tr("Are you sure to abort %1 downloading?").arg(dwl.thread.info[2]) )
					msg.setWindowTitle(self.tr("Abort?"))
					msg.setIcon(QMessageBox.Question)
					nobutton = msg.addButton(self.tr("No"), QMessageBox.ActionRole)
					yesbutton = msg.addButton(self.tr("Yes"), QMessageBox.ActionRole)
					msg.exec_()
					
					if msg.clickedButton() == yesbutton:
						dwl.kill()
					return True
					
	def openDownload(self):
		os.popen( config.DirOpenWith + ' ' + config.loadConf('download_path') )
		
	def about(self):
		a = QString(open(IMGDIR + 'about.html', 'r').read() )
		a.replace("{GBT}", IMGDIR + "gbt.png" )
		QMessageBox.about(self.parent, self.tr('About Qapid'), a )
	
	def aboutQt(self):
		QMessageBox.aboutQt(self, self.tr('About Qt4') )
		
class ConfigWindow(QMainWindow):
	def __init__(self, parent = None):
		QWidget.__init__(self, parent)
		self.parent = parent
		self.ui = configwindow.Ui_ConfigWindow()
		self.ui.setupUi(self)

		screen = QDesktopWidget().screenGeometry()
		size =	self.geometry()

		self.move( ( screen.width() - size.width() ) / 2, ( screen.height() - size.height() ) / 2)

		self.setMaximumWidth( size.width() )
		self.setMaximumHeight( size.height() )
		
		self.setMinimumWidth( size.width() )
		self.setMinimumHeight( size.height() )

		self.setWindowTitle( QString( self.tr("Qapid configuration") ) )

		if not sys.platform == 'darwin':
			self.setWindowIcon( self.parent.parent.tray.icon() )
		
		

		self.ui.pathEdit.setText( QString( config.loadConf( 'download_path' ) ) )
		
		self.ui.rapidUsername.setText( QString( config.loadConf( 'rapidshare_username' ) ) )
		self.ui.rapidPassword.setText( QString( config.loadConf( 'rapidshare_password' ) ) )

		if config.loadConf('show_messages') == 'yes':
			self.ui.showMessages.setCheckState( Qt.Checked )
		else:
			self.ui.showMessages.setCheckState( Qt.Unchecked )
			
		if config.loadConf('show_icon') == 'yes':
			self.ui.showIcon.setCheckState( Qt.Checked )
		else:
			self.ui.showIcon.setCheckState( Qt.Unchecked )

		self.createActions()
		
	def createActions(self):
		QObject.connect( self.ui.pathButton, SIGNAL("clicked()"), self.saveTo )
		QObject.connect( self.ui.okButton, SIGNAL("clicked()"), self.saveConfig )
		QObject.connect( self.ui.cancelButton, SIGNAL("clicked()"), self.close )

	def saveConfig(self):
		config.saveConf( 'download_path', str( self.ui.pathEdit.text() ) )
		config.saveConf( 'rapidshare_username', str( self.ui.rapidUsername.text() ) )
		config.saveConf( 'rapidshare_password', str( self.ui.rapidPassword.text() ) )
		if self.ui.showMessages.checkState() == Qt.Checked:
			config.saveConf( 'show_messages', 'yes' )
		else:
			config.saveConf( 'show_messages', 'no' )
			
		if self.ui.showIcon.checkState() == Qt.Checked:
			config.saveConf( 'show_icon', 'yes' )
			
			self.parent.parent.tray.show()
			QApplication.setQuitOnLastWindowClosed(False)
		else:
			config.saveConf( 'show_icon', 'no')
			if not sys.platform == 'darwin':
				self.parent.show()
				QApplication.setQuitOnLastWindowClosed(True)
			self.parent.parent.tray.hide()
		self.close()

	def saveTo(self, setEdit = True ):
		path = QFileDialog.getExistingDirectory(self, 'Select file(s) download path', self.ui.pathEdit.text(), QFileDialog.ShowDirsOnly)
		if sys.platform == "win32":
			path=unicode(path)

		path = os.path.normcase(path)

		if path and setEdit:
			self.ui.pathEdit.setText( path )

		return path

class LinksWindow(QMainWindow):
	def __init__(self, parent):
		QMainWindow.__init__( self, parent )
		self.parent = parent
		
		self.ui = links.Ui_Dialog()
		self.ui.setupUi(self)
		
		screen = QDesktopWidget().screenGeometry()
		size =	self.geometry()

		self.move( ( screen.width() - size.width() ) / 2, ( screen.height() - size.height() ) / 2)

		self.setMaximumWidth( size.width() )
		self.setMaximumHeight( size.height() )
		
		self.setMinimumWidth( size.width() )
		self.setMinimumHeight( size.height() )

		if not sys.platform == 'darwin':
			self.setWindowIcon( self.parent.parent.tray.icon() )		 

	def accept(self):
		self.parent.download()
		self.close()
		
	def reject(self):
		self.close()

#Shitty code under it ;p

App = QApplication(sys.argv)
translator = QTranslator()
qttranslator = QTranslator()

print QLocale.system().name()

qttranslator.load( ( "qt_%s" % QLocale.system().name() ), QLibraryInfo.location(QLibraryInfo.TranslationsPath) )
translator.load( ( "%s.qm" % QLocale.system().name() ), LOCALE )

App.installTranslator( qttranslator )
App.installTranslator( translator )

x = Tray()
sys.exit(App.exec_()).argv
sys.exit(App.exec_())